import axios from "axios";
import { Message, Loading } from 'element-ui'

// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
const configky = '/api';

const service = axios.create({
    baseURL: configky,
    timeout: 5000
});

let loadingCount = 0;
let loadingInstance = null
function addLoading() {
    if (loadingCount == 0) {
        loadingInstance = Loading.service({
            background: "rgba(1,1,1,0.2)"
        });
    }
    loadingCount++
}

function isCloseLoading() {
    loadingCount--
    if (loadingCount == 0) {
        loadingInstance.close();
    }
}

service.interceptors.request.use(config => {
    config.Loading = config.Loading || true
    if (config.Loading) {
        addLoading()
    }
    return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

service.interceptors.response.use(
    (response) => {
        if (response.config.Loading) {
            isCloseLoading()
        }
        return response.data
    },
    error => {
        console.log('err' + error)
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    })


export default service